import { Body, Controller, Post } from '@midwayjs/core';
import { Goods, GoodsItem, GoodsQuery } from '../entity/goods.entity';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';
import { requestBody } from '../interface/layout';
@Controller('/goods')
export class GoodsController {
  @InjectEntityModel(Goods)
  repoGoods: Repository<Goods>;
  @InjectEntityModel(GoodsItem)
  repoGoodsItem: Repository<GoodsItem>;
  @Post('/insert')
  async insert(@Body() goods: Goods) {
    const gs = new Goods();
    gs.goodsId = String(Date.now()) + Math.floor(Math.random() * 100);
    gs.name = goods.name;
    gs.items = goods.items.map((res, index) => {
      res.goodsItemId = index;
      res.goodsFk = gs.goodsId;
      return res;
    });
    await this.repoGoodsItem.save(gs.items);
    await this.repoGoods.save(gs);
    return <requestBody>{
      code: 0,
      msg: '',
      data: gs,
    };
  }
  @Post('/query')
  async query(@Body() qc: GoodsQuery) {
    const { pageIndex, pageSize, name } = qc;
    const pageStart = (pageIndex - 1) * pageSize;
    const builder = this.repoGoods.createQueryBuilder('gs');
    builder.leftJoin(GoodsItem, 'gi', 'gs.goodsId = gi.goodsFk');
    if (name) {
      builder.orWhere('gs.name like :n ', { n: '%' + name + '%' });
      builder.orWhere('gi.lebal like :l ', { l: '%' + name + '%' });
    }
    builder.skip(pageStart).take(pageSize);
    const r = await builder.printSql().getManyAndCount();
    const result = r[0];
    const ids = result.map(e => e.goodsId);
    const itemsAll = await this.repoGoodsItem.findBy({
      goodsFk: In(ids),
    });
    itemsAll.forEach(gi => {
      const g = result.find(gs => gs.goodsId === gi.goodsFk);

      if (g) {
        g.items.push(gi);
      }
    });
    return <requestBody>{
      code: 0,
      msg: '',
      data: {
        list: r[0],
        total: r[1],
      },
    };
    return;
  }
}
